package com.sunda.spmsoversea.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmscommon.feign.IFeignServiceCommon;
import com.sunda.spmsoversea.entity.*;
import com.sunda.spmsoversea.service.*;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.sunda.spmsoversea.constant.OverseaLogConstant.SAP;
import static com.sunda.spmsoversea.constant.SapConstant.*;
import static com.sunda.spmsoversea.enums.OverseaDeliveryNoteEnum.OVERSEA_DN_WAITING;
import static com.sunda.spmsoversea.enums.OverseaDnEnum.DN_UPDATE;
import static com.sunda.spmsoversea.enums.OverseaDnEnum.DN_WAITING;
import static com.sunda.spmsoversea.enums.OverseaPackageListEnum.OVERSEA_PL_WAITING;

/**
 * @program: spms
 * @description:
 * @author: Wayne Wu
 * @create: 2021-10-22 16:31
 **/
@Service
@Slf4j
public class DataFromSapServiceImpl implements IDataFromSapService {

    /** 海外收货交货单，一般海运收货 */
    @Autowired
    IOverseaDeliveryNoteService iOverseaDeliveryNoteService;
    @Autowired
    IOverseaDeliveryNoteDtlService iOverseaDeliveryNoteDtlService;
    @Autowired
    IOverseaPackageListService iOverseaPackageListService;
    @Autowired
    IOverseaPackageListDtlService iOverseaPackageListDtlService;
    @Autowired
    IOverseaPackageListBoxService iOverseaPackageListBoxService;
    @Autowired
    IOverseaOperateLogService iOverseaOperateLogService;
    @Autowired
    IFeignServiceCommon iFeignServiceCommon;
    @Autowired
    IFormatDataToSapService iFormatDataToSapService;

    /** 海外收货交货单，空运人带/转储/本地采购收货 */
    @Autowired
    IOverseaDnService iOverseaDnService;
    @Autowired
    IOverseaDnDtlService iOverseaDnDtlService;
    @Autowired
    IOverseaPurchaseOrderService iOverseaPurchaseOrderService;
    @Autowired
    IOverseaPurchaseOrderDtlService iOverseaPurchaseOrderDtlService;

    /** 海外收货交货单，一般海运收货 */
    @Override
    public synchronized ResponseResult updateDeliveryNoteRest(String sapPackageList, String deliveryDate, String userId) {
        try {
            if (StringUtils.isEmpty(sapPackageList) && StringUtils.isEmpty(deliveryDate)){
                return ResponseResult.error("请求参数不能为空");
            }
            JSONObject dataToSap = formatData(sapPackageList, deliveryDate);
            JSONObject message = JSONObject.parseObject(iFeignServiceCommon.sendRestToSapCommon(dataToSap));
            log.info("\n=====dataToSap======\n" + dataToSap + "\n=====sapReturnedMessage======\n" + message);
            JSONObject returnData = message.getJSONObject("RESPONSE").getJSONObject("RETURN_DATA");
            if (SAP_SUCCESS.equals(returnData.getString("O_TYPE"))){
                /** IT_LIKP —— 交货单表 */
                JSONArray IT_LIKP = returnData.getJSONArray("IT_LIKP");
                if (IT_LIKP != null){
                    insertOverseaDeliveryNote(IT_LIKP, userId);
                }

                /** IT_LIPS —— 交货单明细表 */
                JSONArray IT_LIPS = returnData.getJSONArray("IT_LIPS");
                if (IT_LIPS != null){
                    insertOverseaDeliveryNoteDtl(IT_LIPS);
                }

                /** IT_ZXDTKO —— 装箱单信息表 */
                JSONArray IT_ZXDTKO = returnData.getJSONArray("IT_ZXDTKO");
                if (IT_ZXDTKO != null){
                    insertOverseaPackageList(IT_ZXDTKO, userId);
                }

                /** IT_ZXDTPO —— 装箱单明细和交货单明细关系表 */
                JSONArray IT_ZXDTPO = returnData.getJSONArray("IT_ZXDTPO");
                if (IT_ZXDTPO != null){
                    insertOverseaPackageListDtl(IT_ZXDTPO);
                }

                /** IT_DNZXD —— 装箱单明细箱码明细关系表 */
                JSONArray IT_DNZXD = returnData.getJSONArray("IT_DNZXD");
                if (IT_DNZXD != null){
                    insertOverseaPackageListBox(IT_DNZXD);
                }

                return ResponseResult.success()
                        .add("dataToSap", dataToSap)
                        .add("sapReturnedMessage", message);
                        //.add("overseaDeliveryNote", iOverseaDeliveryNoteService.getOverseaDnHead(sapDeliveryNote))
                        //.add("overseaDeliveryNoteItem", iOverseaDeliveryNoteService.getOverseaDeliveryNoteItem(sapDeliveryNote));
            } else {
                return ResponseResult.error().add("dataToSap", dataToSap).add("sapReturnedMessage", message);
            }
        }catch (FeignException feignException) {
            feignException.printStackTrace();
            return ResponseResult.error("请求SAP失败 FeignException").add("error", feignException.getMessage());
        } catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error().add("error", e.getMessage());
        }

    }

    JSONObject formatData(String sapPackageList, String deliveryDate){
        Map<String, Object> map = new HashMap<>();
        map.put("iCurrdate", StringUtils.isEmpty(deliveryDate) ? "" : deliveryDate.replaceAll("-", ""));
        map.put("iVbeln", "");
        map.put("iXdnum", StringUtils.isEmpty(sapPackageList) ? "" : sapPackageList);
        map.put("iTraid", "");
        map.put("iSyncDate", "5");
        return iFormatDataToSapService.formatDataToSap(map, null, Z_SPMS_HWCSH, HWCSH);
    }

    /** IT_LIKP —— 交货单表 */
    void insertOverseaDeliveryNote(JSONArray IT_LIKP, String userId){
        int arraySize = IT_LIKP.size();
        if (arraySize > 0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < arraySize; i ++){
                JSONObject doc = IT_LIKP.getJSONObject(i);
                String sapDeliveryNote = doc.getString("VBELN");

                OverseaDeliveryNote overseaDeliveryNote = new OverseaDeliveryNote();
                overseaDeliveryNote.setSapDeliveryNote(sapDeliveryNote);
                overseaDeliveryNote.setSapPackageList(doc.getString("BOLNR"));
                overseaDeliveryNote.setCabinetNumber(doc.getString("TRAID"));
                overseaDeliveryNote.setDeliveryType(doc.getString("LFART"));
                overseaDeliveryNote.setWerksReceive(doc.getString("WERKS"));
                overseaDeliveryNote.setWerksDelivery(doc.getString("FHWRK"));
                overseaDeliveryNote.setSapRemark(doc.getString("ZTEXT"));

                overseaDeliveryNote.setSpmsStatus(OVERSEA_DN_WAITING.getCode());
                overseaDeliveryNote.setCreateDate(sdf.format(new Date()));
                overseaDeliveryNote.setDataStatus(DATA_STATUS_0);
                
                QueryWrapper<OverseaDeliveryNote> queryWrapper =
                        new QueryWrapper<OverseaDeliveryNote>().eq("SAP_DELIVERY_NOTE", sapDeliveryNote);
                OverseaDeliveryNote overseaDeliveryNote1 = iOverseaDeliveryNoteService.getOne(queryWrapper);
                if (overseaDeliveryNote1 != null){
                    if (DATA_STATUS_0.equals(overseaDeliveryNote1.getDataStatus())){
                        iOverseaDeliveryNoteService.update(overseaDeliveryNote, queryWrapper);
                    } else {
                        log.info("=======交货单" + sapDeliveryNote + "已经在收货中更新失败========");
                    }
                } else {
                    overseaDeliveryNote.setUuidDeliveryNote(getUuid());
                    iOverseaDeliveryNoteService.save(overseaDeliveryNote);
                    iOverseaOperateLogService.addOverseaOperateLog(userId, sapDeliveryNote, OVERSEA_DN_WAITING.getDescZh(), OVERSEA_DN_WAITING.getDescEn(), SAP);
                }
            }
        }
    }

    /** IT_LIPS —— 交货单明细表 */
    void insertOverseaDeliveryNoteDtl(JSONArray IT_LIPS){
        int arraySize = IT_LIPS.size();
        if (arraySize > 0){
            /** 根据SAP返回交货单明细信息，获取第一行明细里的 交货单号，根据 交货单号 先删除该交货单所有明细行数据，再新建明细数据； */
            Set<String> dnSet = new HashSet<>();
            for (int i = 0; i < arraySize; i ++){
                String dn = IT_LIPS.getJSONObject(i).getString("VBELN");
                if (StringUtils.isNotEmpty(dn)){
                    dnSet.add(dn);
                }
            }
            QueryWrapper<OverseaDeliveryNoteDtl> deliveryNoteDtlQueryWrapper =
                    new QueryWrapper<OverseaDeliveryNoteDtl>().in("SAP_DELIVERY_NOTE", dnSet).eq("DATA_STATUS", "0");
            iOverseaDeliveryNoteDtlService.remove(deliveryNoteDtlQueryWrapper);

            for (int i = 0; i < arraySize; i ++){
                JSONObject doc = IT_LIPS.getJSONObject(i);
                String sapDeliveryNote = doc.getString("VBELN");
                String sapDeliveryNoteItem = String.valueOf(doc.getInteger("POSNR"));

                OverseaDeliveryNoteDtl overseaDeliveryNoteDtl = new OverseaDeliveryNoteDtl();
                overseaDeliveryNoteDtl.setSapDeliveryNote(sapDeliveryNote);
                overseaDeliveryNoteDtl.setSapDeliveryNoteItem(sapDeliveryNoteItem);
                overseaDeliveryNoteDtl.setMaterialNo(String.valueOf(Long.parseLong(doc.getString("MATNR"))));
                overseaDeliveryNoteDtl.setSapRemark(doc.getString("ARKTX"));
                overseaDeliveryNoteDtl.setWerksDelivery(doc.getString("WERKS"));
                overseaDeliveryNoteDtl.setWhsLocationCodeDelivery(doc.getString("LGORT"));
                overseaDeliveryNoteDtl.setReceivableQtyUnitSales(doc.getDoubleValue("LFIMG"));
                overseaDeliveryNoteDtl.setBasicUnit(doc.getString("MEINS"));
                overseaDeliveryNoteDtl.setMovementType(doc.getString("BWART"));
                overseaDeliveryNoteDtl.setUnitSales(doc.getString("VRKME"));
                overseaDeliveryNoteDtl.setPurchaseNo(doc.getString("VGBEL"));
                overseaDeliveryNoteDtl.setPurchaseNoItem(String.valueOf(doc.getInteger("VGPOS")));
                overseaDeliveryNoteDtl.setReceivableQtyBasicUnit(doc.getDoubleValue("LGMNG"));
                overseaDeliveryNoteDtl.setWerksReceive(doc.getString("SHWRK"));
                overseaDeliveryNoteDtl.setColorNo(doc.getString("KANNR"));
                overseaDeliveryNoteDtl.setDataStatus(DATA_STATUS_0);

                QueryWrapper<OverseaDeliveryNoteDtl> queryWrapper = new QueryWrapper<OverseaDeliveryNoteDtl>()
                        .eq("SAP_DELIVERY_NOTE", sapDeliveryNote).eq("SAP_DELIVERY_NOTE_ITEM", sapDeliveryNoteItem);
                OverseaDeliveryNoteDtl overseaDeliveryNoteDtl1 = iOverseaDeliveryNoteDtlService.getOne(queryWrapper);
                if (overseaDeliveryNoteDtl1 != null){
                    if (DATA_STATUS_0.equals(overseaDeliveryNoteDtl1.getDataStatus())){
                        iOverseaDeliveryNoteDtlService.update(overseaDeliveryNoteDtl, queryWrapper);
                    } else {
                        log.info("=======交货单" + sapDeliveryNote + " 行号" + sapDeliveryNoteItem + "已经在收货中更新失败========");
                    }
                } else {
                    iOverseaDeliveryNoteDtlService.save(overseaDeliveryNoteDtl);
                }
            }
        }
    }

    /** IT_ZXDTKO —— 装箱单信息表 */
    void insertOverseaPackageList(JSONArray IT_ZXDTKO, String userId){
        int arraySize = IT_ZXDTKO.size();
        if (arraySize > 0){
            for (int i = 0; i < arraySize; i ++){
                JSONObject doc = IT_ZXDTKO.getJSONObject(i);
                String sapPackageList = doc.getString("XDNUM");

                OverseaPackageList overseaPackageList = new OverseaPackageList();
                overseaPackageList.setSapPackageList(doc.getString("XDNUM"));
                overseaPackageList.setMerchandiser(doc.getString("MERCH"));
                overseaPackageList.setCabinetModel(doc.getString("MAGRV"));
                overseaPackageList.setFromPort(doc.getString("SPORT"));
                overseaPackageList.setToPort(doc.getString("EPORT"));
                overseaPackageList.setDataStatus(DATA_STATUS_0);

                QueryWrapper<OverseaPackageList> queryWrapper =
                        new QueryWrapper<OverseaPackageList>().eq("SAP_PACKAGE_LIST", sapPackageList);
                OverseaPackageList overseaPackageList1 = iOverseaPackageListService.getOne(queryWrapper);
                if (overseaPackageList1 != null){
                    if (DATA_STATUS_0.equals(overseaPackageList1.getDataStatus())){
                        iOverseaPackageListService.update(overseaPackageList, queryWrapper);
                    } else {
                        log.info("=======装箱单" + sapPackageList + "已经在收货中更新失败========");
                    }
                } else {
                    overseaPackageList.setUuidPackageList(getUuid());

                    iOverseaPackageListService.save(overseaPackageList);
                    iOverseaOperateLogService.addOverseaOperateLog(userId, sapPackageList, OVERSEA_PL_WAITING.getDescZh(), OVERSEA_PL_WAITING.getDescEn(), SAP);
                }
            }
        }
    }

    /** IT_ZXDTPO —— 装箱单明细和交货单明细关系表 */
    void insertOverseaPackageListDtl(JSONArray IT_ZXDTPO){
        int arraySize = IT_ZXDTPO.size();
        if (arraySize > 0){

            /** 根据SAP返回装箱单明细和交货单明细关系表信息，获取第一行明细里的 装箱单号，根据 装箱单号 先删除该装箱单所有明细行数据，再新建明细数据； */
            Set<String> packageListSet = new HashSet<>();
            for (int i = 0; i < arraySize; i ++){
                String sapPackageList = IT_ZXDTPO.getJSONObject(i).getString("XDNUM");
                if (StringUtils.isNotEmpty(sapPackageList)){
                    packageListSet.add(sapPackageList);
                }
            }
            QueryWrapper<OverseaPackageListDtl> packageListDtlQueryWrapper =
                    new QueryWrapper<OverseaPackageListDtl>().in("SAP_PACKAGE_LIST", packageListSet).eq("DATA_STATUS", "0");
            iOverseaPackageListDtlService.remove(packageListDtlQueryWrapper);

            for (int i = 0; i < arraySize; i ++){
                JSONObject doc = IT_ZXDTPO.getJSONObject(i);
                String sapPackageList = doc.getString("XDNUM");
                String sapPackageListItem = String.valueOf(doc.getInteger("POSNR"));

                OverseaPackageListDtl overseaPackageListDtl = new OverseaPackageListDtl();
                overseaPackageListDtl.setSapPackageList(sapPackageList);
                overseaPackageListDtl.setSapPackageListItem(sapPackageListItem);
                overseaPackageListDtl.setSapDeliveryNote(doc.getString("VBELN_OT"));
                overseaPackageListDtl.setPurchaseNo(doc.getString("ZPONO_CC"));
                overseaPackageListDtl.setPurchaseNoItem(String.valueOf(doc.getInteger("ZPOITEM_CC")));
                overseaPackageListDtl.setDataStatus(DATA_STATUS_0);

                QueryWrapper<OverseaPackageListDtl> queryWrapper = new QueryWrapper<OverseaPackageListDtl>()
                        .eq("SAP_PACKAGE_LIST", sapPackageList).eq("SAP_PACKAGE_LIST_ITEM", sapPackageListItem);
                OverseaPackageListDtl overseaPackageListDtl1 = iOverseaPackageListDtlService.getOne(queryWrapper);
                if (overseaPackageListDtl1 != null){
                    if (DATA_STATUS_0.equals(overseaPackageListDtl1.getDataStatus())){
                        iOverseaPackageListDtlService.update(overseaPackageListDtl, queryWrapper);
                    } else {
                        log.info("=======装箱单" + sapPackageList + " 行号" + sapPackageListItem + "已经在收货中更新失败========");
                    }
                } else {
                    iOverseaPackageListDtlService.save(overseaPackageListDtl);
                }
            }
        }
    }

    /** IT_DNZXD —— 装箱单明细箱码明细关系表 */
    void insertOverseaPackageListBox(JSONArray IT_DNZXD){
        int arraySize = IT_DNZXD.size();
        if (arraySize > 0){

            /** 根据SAP返回 装箱单明细箱码明细关系表 信息，获取第一行明细里的 装箱单号，根据 装箱单号 先删除该装箱单所有明细行数据，再新建明细数据； */
            Set<String> packageListSet = new HashSet<>();
            for (int i = 0; i < arraySize; i ++){
                String sapPackageList = IT_DNZXD.getJSONObject(i).getString("XDNUM");
                if (StringUtils.isNotEmpty(sapPackageList)){
                    packageListSet.add(sapPackageList);
                }
            }
            QueryWrapper<OverseaPackageListBox> packageListBoxQueryWrapper =
                    new QueryWrapper<OverseaPackageListBox>().in("SAP_PACKAGE_LIST", packageListSet).eq("DATA_STATUS", "0");
            iOverseaPackageListBoxService.remove(packageListBoxQueryWrapper);

            for (int i = 0; i < arraySize; i ++){
                JSONObject doc = IT_DNZXD.getJSONObject(i);

                String sapPackageList = doc.getString("XDNUM");
                String sapPackageListItem = String.valueOf(doc.getInteger("ZPOSNR"));
                String boxNote = doc.getString("PACKAGE_CODE");
                String boxNoteItem = String.valueOf(doc.getInteger("SERIAL"));

                OverseaPackageListBox overseaPackageListBox = new OverseaPackageListBox();
                overseaPackageListBox.setSapPackageList(sapPackageList);
                overseaPackageListBox.setSapPackageListItem(sapPackageListItem);
                overseaPackageListBox.setBoxNote(boxNote);
                overseaPackageListBox.setBoxNoteItem(boxNoteItem);
                overseaPackageListBox.setMaterialNo(String.valueOf(Long.parseLong(doc.getString("MATNR"))));
                overseaPackageListBox.setReceivableQtyBasicUnit(doc.getDoubleValue("GNCKSL"));
                overseaPackageListBox.setBasicUnit(doc.getString("MEINS"));
                overseaPackageListBox.setBoxStatus("0");
                overseaPackageListBox.setDataStatus(DATA_STATUS_0);
                overseaPackageListBox.setDemandNo(doc.getString("DEMAND_NO"));
                overseaPackageListBox.setDemandItem(String.valueOf(doc.getInteger("DEMAND_POSNR")));
                overseaPackageListBox.setDemander(doc.getString("DEMANDER"));

                QueryWrapper<OverseaPackageListBox> queryWrapper = new QueryWrapper<OverseaPackageListBox>()
                        .eq("BOX_NOTE", boxNote).eq("BOX_NOTE_ITEM", boxNoteItem);
                OverseaPackageListBox overseaPackageListBox1 = iOverseaPackageListBoxService.getOne(queryWrapper);
                if (overseaPackageListBox1 != null){
                    if (DATA_STATUS_0.equals(overseaPackageListBox1.getDataStatus())){
                        iOverseaPackageListBoxService.update(overseaPackageListBox, queryWrapper);
                    } else {
                        log.info("=======装箱单" + sapPackageList + " 行号" + sapPackageListItem + "，箱码" + boxNote + " 箱码行号" + boxNoteItem + "已经在收货中更新失败========");
                    }
                } else {
                    iOverseaPackageListBoxService.save(overseaPackageListBox);
                }
            }
        }
    }

    String getUuid(){
        return UUID.randomUUID().toString().replaceAll("-","").toLowerCase();
    }


    /** 海外收货交货单，空运人带/转储/本地采购收货 */
    @Override
    public synchronized ResponseResult updateOverseaDnRest(String sapDeliveryNote, String businessType, String purchaseOrder,
                                              String deliveryDateS, String deliveryDateE, String werks, String userId) {
        try {
            if (StringUtils.isEmpty(businessType)){
                return ResponseResult.error("请求参数业务标识不能为空");
            }
            JSONObject dataToSap = formatDataGetDn(sapDeliveryNote, businessType, purchaseOrder, deliveryDateS, deliveryDateE, werks);
            JSONObject message = JSONObject.parseObject(iFeignServiceCommon.sendRestToSapCommon(dataToSap));
            log.info("\n=====dataToSap======\n" + dataToSap + "\n=====sapReturnedMessage======\n" + message);
            JSONObject returnData = message.getJSONObject("RESPONSE").getJSONObject("RETURN_DATA");
            if (SAP_SUCCESS.equals(returnData.getString("O_TYPE"))){
                String sapBusinessType = returnData.getString("O_FLAG");
                /** IT_LIKP —— 交货单表 ——— 空运人带/转储/本地采购收货 */
                JSONArray IT_LIKP = returnData.getJSONArray("IT_LIKP");
                if (IT_LIKP != null){
                    insertOverseaDn(IT_LIKP, sapBusinessType,userId);
                }

                /** IT_LIPS —— 交货单明细表 ——— 空运人带/转储/本地采购收货 */
                JSONArray IT_LIPS = returnData.getJSONArray("IT_LIPS");
                if (IT_LIPS != null){
                    insertOverseaDnDtl(IT_LIPS);
                }

                /** IT_EKKO —— 采购订单表表头 ——— 空运人带/转储/本地采购收货 */
                JSONArray IT_EKKO = returnData.getJSONArray("IT_EKKO");
                if (IT_EKKO != null){
                    insertOverseaPurchaseOrder(IT_EKKO, sapBusinessType);
                }

                /** IT_EKPO —— 采购订单表明细 ——— 空运人带/转储/本地采购收货 */
                JSONArray IT_EKPO = returnData.getJSONArray("IT_EKPO");
                if (IT_EKPO != null){
                    insertOverseaPurchaseOrderDtl(IT_EKPO);
                }

                return ResponseResult.success()
                        .add("dataToSap", dataToSap)
                        .add("sapReturnedMessage", message);
            } else {
                return ResponseResult.error().add("dataToSap", dataToSap).add("sapReturnedMessage", message);
            }
        } catch (FeignException feignException) {
            feignException.printStackTrace();
            return ResponseResult.error("请求SAP失败 FeignException").add("error", feignException.getMessage());
        } catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error().add("error", e.getMessage());
        }
    }

    JSONObject formatDataGetDn(String sapDeliveryNote, String businessType, String purchaseOrder,
                               String deliveryDateS, String deliveryDateE, String werks){
        Map<String, Object> map = new HashMap<>();
        map.put("iDatee", StringUtils.isEmpty(deliveryDateE) ? "" : deliveryDateE.replaceAll("-", ""));
        map.put("iDates", StringUtils.isEmpty(deliveryDateS) ? "" : deliveryDateS.replaceAll("-", ""));
        map.put("iEbeln", StringUtils.isEmpty(purchaseOrder) ? "" : purchaseOrder);
        map.put("iFlag", businessType);
        map.put("iVbeln", StringUtils.isEmpty(sapDeliveryNote) ? "" : sapDeliveryNote);
        map.put("iWerks", StringUtils.isEmpty(werks) ? "" : werks);
        return iFormatDataToSapService.formatDataToSap(map, null, Z_SPMS_GETHWDN, GETHWDN);
    }

    /** IT_LIKP —— 交货单表 ——— 空运人带/转储/本地采购收货 */
    synchronized void insertOverseaDn(JSONArray IT_LIKP, String sapBusinessType, String userId){
        int arraySize = IT_LIKP.size();
        if (arraySize > 0){
            for (int i = 0; i < arraySize; i ++){
                JSONObject doc = IT_LIKP.getJSONObject(i);
                String sapDeliveryNote = doc.getString("VBELN");

                OverseaDn overseaDn = new OverseaDn();
                overseaDn.setSapDeliveryNote(sapDeliveryNote);
                overseaDn.setWerksReceive(doc.getString("WERKS"));
                overseaDn.setSapCreateDate(doc.getString("ERDAT"));
                overseaDn.setDeliveryDate(doc.getString("LFDAT"));
                overseaDn.setBusinessType(sapBusinessType);

                overseaDn.setSpmsStatus(DN_WAITING.getCode());
                overseaDn.setDataStatus(DATA_STATUS_0);

                QueryWrapper<OverseaDn> queryWrapper = new QueryWrapper<OverseaDn>().eq("SAP_DELIVERY_NOTE", sapDeliveryNote);
                OverseaDn dn = iOverseaDnService.getOne(queryWrapper);
                if (dn != null){
                    if (DATA_STATUS_0.equals(dn.getDataStatus())){
                        iOverseaDnService.update(overseaDn, queryWrapper);
                        iOverseaOperateLogService.addOverseaOperateLog(userId, sapDeliveryNote, DN_UPDATE.getDescZh(), DN_UPDATE.getDescEn(), SAP);
                    } else {
                        log.info("=======空运人带/转储/本地采购 交货单" + sapDeliveryNote + "已经在收货中更新失败========");
                    }
                } else {
                    overseaDn.setUuidDeliveryNote(getUuid());
                    iOverseaDnService.save(overseaDn);
                    iOverseaOperateLogService.addOverseaOperateLog(userId, sapDeliveryNote, DN_WAITING.getDescZh(), DN_WAITING.getDescEn(), SAP);
                }

            }
        }
    }

    /** IT_LIPS —— 交货单明细表 ——— 空运人带/转储/本地采购收货 */
    synchronized void insertOverseaDnDtl(JSONArray IT_LIPS){
        int arraySize = IT_LIPS.size();
        if (arraySize > 0) {

            /** 交货单明细信息，在更新之前先将DN明细行里数据状态字段值为0的行全都删除，再依据SAP返回信息建立新的交货单明细行 */
            Set<String> dnSet = new HashSet<>();
            for (int i = 0; i < arraySize; i++) {
                String dn = IT_LIPS.getJSONObject(i).getString("VBELN");
                if (StringUtils.isNotEmpty(dn)){
                    dnSet.add(dn);
                }
            }
            QueryWrapper<OverseaDnDtl> overseaDnDtlQueryWrapper =
                    new QueryWrapper<OverseaDnDtl>().in("SAP_DELIVERY_NOTE", dnSet).eq("DATA_STATUS", "0");
            iOverseaDnDtlService.remove(overseaDnDtlQueryWrapper);

            for (int i = 0; i < arraySize; i++) {
                JSONObject doc = IT_LIPS.getJSONObject(i);

                String sapDeliveryNote = doc.getString("VBELN");
                String sapDeliveryNoteItem = String.valueOf(doc.getInteger("POSNR"));

                OverseaDnDtl overseaDnDtl = new OverseaDnDtl();
                overseaDnDtl.setSapDeliveryNote(sapDeliveryNote);
                overseaDnDtl.setSapDeliveryNoteItem(sapDeliveryNoteItem);
                overseaDnDtl.setWerksReceive(doc.getString("WERKS"));
                overseaDnDtl.setSapPurchaseOrder(doc.getString("VGBEL"));
                overseaDnDtl.setSapPurchaseOrderItem(String.valueOf(doc.getInteger("VGPOS")));
                overseaDnDtl.setWerksDelivery(doc.getString("WERKS_FH"));
                overseaDnDtl.setWhsLocationCodeDelivery(doc.getString("LGORT"));
                overseaDnDtl.setMaterialNo(StringUtils.isEmpty(doc.getString("MATNR")) ?
                        "" : String.valueOf(Long.parseLong(doc.getString("MATNR"))));
                overseaDnDtl.setUnitSales(doc.getString("VRKME"));
                overseaDnDtl.setReceivableQtyUnitSales(doc.getDoubleValue("LFIMG"));
                overseaDnDtl.setBasicUnit(doc.getString("MEINS"));
                overseaDnDtl.setReceivableQtyBasicUnit(doc.getDoubleValue("LGMNG"));
                overseaDnDtl.setBoxNote(doc.getString("PACKAGE_CODE"));
                overseaDnDtl.setBoxNoteItem(String.valueOf(doc.getInteger("SERIAL")));
                overseaDnDtl.setDomesticActualQty(doc.getDoubleValue("GNCKSL"));
                overseaDnDtl.setDemandNo(doc.getString("DEMAND_NO"));
                overseaDnDtl.setDemandItem(String.valueOf(doc.getInteger("DEMAND_POSNR")));
                overseaDnDtl.setDemander(doc.getString("DEMANDER"));
                overseaDnDtl.setDataStatus(DATA_STATUS_0);

                QueryWrapper<OverseaDnDtl> queryWrapper = new QueryWrapper<OverseaDnDtl>()
                        .eq("SAP_DELIVERY_NOTE", sapDeliveryNote).eq("SAP_DELIVERY_NOTE_ITEM", sapDeliveryNoteItem);
                OverseaDnDtl dnDtl = iOverseaDnDtlService.getOne(queryWrapper);

                if (dnDtl != null){
                    if (DATA_STATUS_0.equals(dnDtl.getDataStatus())){
                        iOverseaDnDtlService.update(overseaDnDtl, queryWrapper);
                    } else {
                        log.info("=======空运人带/转储/本地采购 交货单" + sapDeliveryNote + " 行号" + sapDeliveryNoteItem + "已经在收货中更新失败========");
                    }
                } else {
                    iOverseaDnDtlService.save(overseaDnDtl);
                }

            }
        }
    }

    /** IT_EKKO —— 采购订单表表头 ——— 空运人带/转储/本地采购收货 */
    synchronized void insertOverseaPurchaseOrder(JSONArray IT_EKKO, String sapBusinessType){
        int arraySize = IT_EKKO.size();
        if (arraySize > 0) {
            for (int i = 0; i < arraySize; i ++) {
                JSONObject doc = IT_EKKO.getJSONObject(i);
                String sapPurchaseOrder = doc.getString("EBELN");

                OverseaPurchaseOrder overseaPurchaseOrder = new OverseaPurchaseOrder();
                overseaPurchaseOrder.setSapPurchaseOrder(sapPurchaseOrder);
                overseaPurchaseOrder.setBusinessType(sapBusinessType);
                overseaPurchaseOrder.setSapCreateDate(doc.getString("AEDAT"));
                overseaPurchaseOrder.setVoucherType(doc.getString("BSART"));
                overseaPurchaseOrder.setPurchaseGroup(doc.getString("EKGRP"));
                overseaPurchaseOrder.setPurchaseOrg(doc.getString("EKORG"));
                overseaPurchaseOrder.setSupplierCode(doc.getString("LIFNR"));
                overseaPurchaseOrder.setSupplierDesc("");
                overseaPurchaseOrder.setCreateUser(doc.getString("ERNAM"));
                overseaPurchaseOrder.setDataStatus(DATA_STATUS_0);

                QueryWrapper<OverseaPurchaseOrder> queryWrapper = new QueryWrapper<OverseaPurchaseOrder>().eq("SAP_PURCHASE_ORDER", sapPurchaseOrder);
                OverseaPurchaseOrder purchaseOrder = iOverseaPurchaseOrderService.getOne(queryWrapper);

                if (purchaseOrder != null){
                    if (DATA_STATUS_0.equals(purchaseOrder.getDataStatus())){
                        iOverseaPurchaseOrderService.update(overseaPurchaseOrder, queryWrapper);
                    } else {
                        log.info("=======空运人带/转储/本地采购 采购订单" + sapPurchaseOrder + "已经在收货中更新失败========");
                    }
                } else {
                    overseaPurchaseOrder.setUuidPurchaseOrder(getUuid());
                    iOverseaPurchaseOrderService.save(overseaPurchaseOrder);
                }
            }
        }
    }

    /** IT_EKPO —— 采购订单表明细 ——— 空运人带/转储/本地采购收货 */
    synchronized void insertOverseaPurchaseOrderDtl(JSONArray IT_EKPO){
        int arraySize = IT_EKPO.size();
        if (arraySize > 0) {

            /** 采购订单表明细信息，在更新之前先将PO明细行里数据状态字段值为0的行全都删除，再依据SAP返回信息建立新的采购订单单明细行 */
            Set<String> poSet = new HashSet<>();
            for (int i = 0; i < arraySize; i++) {
                String dn = IT_EKPO.getJSONObject(i).getString("EBELN");
                if (StringUtils.isNotEmpty(dn)){
                    poSet.add(dn);
                }
            }
            QueryWrapper<OverseaPurchaseOrderDtl> purchaseOrderDtlQueryWrapper =
                    new QueryWrapper<OverseaPurchaseOrderDtl>().in("SAP_PURCHASE_ORDER", poSet).eq("DATA_STATUS", "0");
            iOverseaPurchaseOrderDtlService.remove(purchaseOrderDtlQueryWrapper);

            for (int i = 0; i < arraySize; i ++){
                JSONObject doc = IT_EKPO.getJSONObject(i);
                String sapPurchaseOrder = doc.getString("EBELN");
                String sapPurchaseOrderItem = String.valueOf(doc.getInteger("EBELP"));

                OverseaPurchaseOrderDtl overseaPurchaseOrderDtl = new OverseaPurchaseOrderDtl();
                overseaPurchaseOrderDtl.setSapPurchaseOrder(sapPurchaseOrder);
                overseaPurchaseOrderDtl.setSapPurchaseOrderItem(sapPurchaseOrderItem);
                overseaPurchaseOrderDtl.setWhsLocationCodeReceive(doc.getString("LGORT"));
                overseaPurchaseOrderDtl.setMaterialNo(StringUtils.isEmpty(doc.getString("MATNR")) ?
                        "" : String.valueOf(Long.parseLong(doc.getString("MATNR"))));
                overseaPurchaseOrderDtl.setMaterialZhDesc(doc.getString("TXZ01"));
                overseaPurchaseOrderDtl.setBasicUnit(doc.getString("MEINS"));
                overseaPurchaseOrderDtl.setReceivableQtyBasicUnit(doc.getDoubleValue("MENGE"));
                overseaPurchaseOrderDtl.setReturnMark(doc.getString("RETPO"));
                overseaPurchaseOrderDtl.setWerksReceive(doc.getString("WERKS"));
                overseaPurchaseOrderDtl.setDataStatus(DATA_STATUS_0);

                QueryWrapper<OverseaPurchaseOrderDtl> queryWrapper = new QueryWrapper<OverseaPurchaseOrderDtl>()
                        .eq("SAP_PURCHASE_ORDER", sapPurchaseOrder).eq("SAP_PURCHASE_ORDER_ITEM", sapPurchaseOrderItem);
                OverseaPurchaseOrderDtl purchaseOrderDtl = iOverseaPurchaseOrderDtlService.getOne(queryWrapper);

                if (purchaseOrderDtl != null){
                    if (DATA_STATUS_0.equals(purchaseOrderDtl.getDataStatus())){
                        iOverseaPurchaseOrderDtlService.update(overseaPurchaseOrderDtl, queryWrapper);
                    } else {
                        log.info("=======空运人带/转储/本地采购 采购订单" + sapPurchaseOrder + " 行号" + sapPurchaseOrderItem + "已经在收货中更新失败========");
                    }
                } else {
                    iOverseaPurchaseOrderDtlService.save(overseaPurchaseOrderDtl);
                }

            }
        }
    }
}











